import 'package:flutter/material.dart';

class CounterDemo extends StatefulWidget {
  @override
  _CounterDemoState createState() => _CounterDemoState();
}

class _CounterDemoState extends State<CounterDemo> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('计数器')),
      body: AnimationedCounter(
        value: _counter,
        duration: Duration(seconds: 1),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class AnimationedCounter extends StatelessWidget {
  final int value;
  final Duration duration;

  AnimationedCounter({@required this.value, @required this.duration});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 300,
        height: 100,
        child: TweenAnimationBuilder(
          duration: duration,
          tween: Tween(end: value.toDouble()),
          builder: (BuildContext context, double value, Widget child) {
            final int whole = value ~/ 1;
            final double decinal = value - whole;

            return Stack(
              children: [
                Positioned(
                  top: -100 * decinal,
                  child: Opacity(
                    opacity: 1 - decinal,
                    child: Text('$whole', style: TextStyle(fontSize: 100)),
                  ),
                ),
                Positioned(
                  top: 100 - decinal * 100,
                  child: Opacity(
                    opacity: decinal,
                    child:
                        Text('${whole + 1}', style: TextStyle(fontSize: 100)),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
